from django.contrib.auth import login
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
import json
from datetime import datetime
from django_redis import get_redis_connection
from utils.views import LoginRequiredJSONMixin
from apps.houses.models import House
from apps.order.models import Order
from Love_house.settings import QINIU_DOMIN_PREFIX
from utils.response_code import RET


# Create your views here.


class OrdersView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 获取数据
        data = json.loads(request.body.decode())
        house_id = data.get('house_id')  # 房屋id
        start_date = data.get('start_date')  # 开始日期
        end_date = data.get('end_date')  # 结束日期
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '参数不全'})
        # 判断是否登录
        user = request.user
        if user.is_authenticated:
            start_date = datetime.strptime(start_date, "%Y-%m-%d")
            end_date = datetime.strptime(end_date, "%Y-%m-%d")
            # assert start_date <= end_date

            # 查询房子是否存在
            try:
                house = House.objects.get(id=house_id)
            except House.DoesNotExist:
                return JsonResponse({'errno': RET.NODATA, 'errmsg': '房子不存在!'})

            # 计算预定的天数
            days = (end_date - start_date).days + 1  # datetime.timedelta

            # 预定的房屋是否是房东自己
            if user.id == house.user.id:
                return JsonResponse({'errno': RET.DATAEXIST, 'errmsg': '不能预定自己的房屋'})
            try:
                # 查询时间冲突的订单数
                count = Order.objects.filter(house=house_id,
                                             begin_date__lt=end_date,
                                             end_date__gt=start_date).count()
            except Exception as e:

                return JsonResponse({'errno': RET.DATAERR, 'errmsg': '检查出错，请稍后重试'})

            if count > 0:
                return JsonResponse({'errno': RET.DATAEXIST, 'errmsg': '房屋已预定'})

            # 预定总额
            amount = days * house.price

            # 保存订单数据
            order = Order.objects.create(
                house_id=house_id,
                user_id=user.id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=amount
            )
            order.save()
            # 设置session 实现状态保持
            login(request, order.user)
            # 设置cookie
            response = JsonResponse({'errno': RET.OK, 'errmsg': 'OK', 'data': {"order_id": order.id}})
            # response.set_cookie('username', order.user)
            return response

        else:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '用户未登录!!'})

    def get(self, request):
        '''获取订单的用户信息'''
        # 接收请求
        # json_dict = json.loads(request.body.decode())

        # 获取用户id

        user_id = request.user.id
        # 判断用户的身份，是想通过用户身份作为房客查询订单
        # 还是想要作为房东查询别人下的订单
        role = request.GET.get("role")
        try:
            # 查询订单信息
            if "landlord" == role:
                # 以房东的身份查询订单,并查询自己的房子数量
                houses = House.objects.filter(user=user_id).all()
                houses_ids = [house.id for house in houses]
                # 再查询预定了自己房子的订单
                orders = Order.objects.filter(house__in=houses_ids).order_by('-create_time').all()
            else:
                orders = Order.objects.filter(user=user_id).order_by('-create_time').all()
        except Exception as e:

            return JsonResponse({'errno': RET.NODATA, 'errmsg': '没有查到此信息'})

            # 将订单信息转换为字典数据
        orders_dict_list = []
        if orders:
            for order in orders:
                orders_dict_list.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": QINIU_DOMIN_PREFIX + str(order.house.index_image_url),
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM[int(order.status)],
                    "title": order.house.title
                })
        return JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': {"orders": orders_dict_list}})


class RefuseAcceptView(LoginRequiredJSONMixin, View):
    """ 接单拒单 """
    def put(self, request, order_id):
        # 获取数据
        user = request.user
        data = json.loads(request.body.decode())
        action = data.get('action')
        reason = data.get('reason')
        # 验证参数
        if action not in ('accept', 'reject'):
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '参数不全'})

        try:
            # 查询订单状态为待接单的
            order = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS['WAIT_ACCEPT']).first()
            house = order.house  # 判断是否为房屋主人自己的房子
        except Exception:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '暂时没有待接单或房东只能修改属于自己房子的订单'})
        except House.DoesNotExist:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '房东只能修改属于自己房子的订单'})


        # 确保房东只能修改属于自己房子的订单
        if not order or house.user_id != user.id:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '操作无效'})

        if action == 'accept':
            # 接单，将订单状态设置为等待支付
            # Order.objects.filter(id=order.id).update()
            order.status = Order.ORDER_STATUS['WAIT_PAYMENT']

        elif action == 'reject':
            # 拒单，要求用户传递拒单原因
            # reason = req_data.get("reason")
            if not reason:
                return JsonResponse({'errno': RET.NODATA, 'errmsg': '参数错误'})
            order.status = Order.ORDER_STATUS["REJECTED"]
            order.comment = reason

        order.save()

        return JsonResponse({"errno": RET.OK, 'errmsg': '操作成功!'})


class Orderevaluateview(View):

    def put(self, request, order_id):
        """保存评论信息
        参数：订单编号
        """
        # 获取用户 id
        user_id = request.user.id

        # 获取参数
        req_data = json.loads(request.body.decode())
        comment = req_data.get("comment")

        if not comment:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '参数错误'})

        # 根据订单编号,检验该订单是自己下的订单,并且处于待评论的状态, 否则不予许评论
        try:
            order = Order.objects.filter(id=order_id, user=user_id,
                                         status=Order.ORDER_STATUS['WAIT_COMMENT']).first()
            house = order.house
        except Exception as e:

            return JsonResponse({'errno': RET.DBERR, 'errmsg': '无法获取订单数据'})

        if not order:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '无法操作'})

        # 设置redis
        redis = get_redis_connection('order')

        # 保存评论
        try:
            # 修改订单状态为"已完成"
            order.status = Order.ORDER_STATUS['COMPLETE']
            # 添加评论内容
            order.comment = comment
            # 房子表中该房子被订单数量加 1
            house.order_count += 1
            # 提交
            login(request, order.user)
        except Exception as e:
            return JsonResponse({'errno': RET.DBERR, 'errmsg': '操作失败'})

        # 因为房屋详情中有订单的评价信息，为了让最新的评价信息展示在房屋详情中，
        # 所以删除redis中关于本订单房屋的详情缓存
        try:
            redis.delete("house_info_%s" % order.house.id)
        except Exception as e:
            # logger.error(e)
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '没有信息'})

        order.save()

        return JsonResponse({"errno": RET.OK, 'errmsg': 'ok'})
